// pages/user/index/index.js
import {getInfo, getAssets} from "../../../service/User";
import {getResult} from "../../../service/Questionnaire";
import {hiddenPhoneNumber} from "../../../utils/Util";
import Toast from "@vant/weapp/toast/toast";
import {getStorageSync, removeStorageSync, setStorage} from "../../../utils/Storage";
import Storage from "../../../utils/Storage";
import {addOnce, remove} from "../../../utils/Notification";
import Dialog from "@vant/weapp/dialog/dialog";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {
            name: "",
            type: 1,
            typeName: "",
            tel: ""
        },
        assets: {
            total: "",
            change: "",
            chiyou: 0,
            shuhui: 0,
            pilou: 0
        },
        result: {},
        showBottom: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        Toast.loading({
            mask: true,
            duration: 0, // 持续展示 toast
            message: "加载中...",
            selector: "#van-toast"
        });
        this.getUserInfo();
    },

    /*
    * 获取用户信息
    * */
    getUserInfo: async function () {
        try {
            let res = await getInfo();
            await this.getUserAssets();
            await this.getResult();
            let name, typeName;
            switch (res.type) {
                case 1: //个人
                    name = res.name;
                    typeName = "个人客户";
                    break
                case 2: //机构
                    name = res.org_name;
                    typeName = "机构客户";
                    break
                case 3: //产品客户
                    name = res.org_name || res.name;
                    typeName = "产品客户";
                    break
                default:
                    name = "游客";
                    typeName = "潜在客户";
                    break
            }
            this.setData({
                userInfo: {
                    name: name,
                    type: res.type,
                    typeName: typeName,
                    tel: hiddenPhoneNumber(res.tel)
                },
                showBottom: true
            })
            setStorage("userInfo", res);
        } catch (e) {
            this.setData({showBottom: false})
            console.error(e)
        } finally {
            Toast.clear();
        }
    },

    /*
    * 获取个人资产
    * */
    getUserAssets: async function () {
        let res = await getAssets();
        let getVal = function (val) {
            let newVal = "";
            let valArr = val.toString().split(".");
            let _val1 = valArr[0].toString().split("");
            let _val2 = valArr[1];
            let diff = _val1.length % 3;
            if (diff > 0) {
                newVal = _val1.splice(0, diff).join("") + ",";
            }
            for (let i = 0; i < _val1.length; i ++) {
                if (i > 0 && (i + 1) % 3 === 0) {
                    newVal = newVal + _val1[i] + ",";
                } else {
                    newVal += _val1[i];
                }
            }
            newVal = newVal.substr(0, newVal.length - 1);
            if (!_val2) {
                newVal = newVal + ".00";
            } else if (_val2 && _val2.length === 1) {
                newVal = newVal + "." + _val2 + "0";
            } else if (_val2) {
                newVal = newVal + "." + _val2;
            }
            return newVal
        }
        this.setData({
            assets: {
                total: getVal(res.total),
                change: getVal(res.change),
                chiyou: res.chiyou,
                shuhui: res.shuhui,
                pilou: res.pilou
            }
        })
    },

    /*
    * 获取评测结果
    * */
    getResult: async function () {
        let res = await getResult();
        this.setData({result: res})
    },

    /*
    * 点击事件
    * 根据name 值不同跳转不同页面
    * */
    bindNavigator: async function (e) {
        try {
            const that = this;
            let name = e.currentTarget.dataset.name;
            let status = await this._checkedLogin();
            if (!status) {return false}
            switch (name) {
                case "hold": //我的持仓
                    wx.navigateTo({url: "/packageUser/pages/hold-list/index"});
                    break
                case "transaction": //交易明细
                    wx.navigateTo({url: "/packageUser/pages/transaction-list/index"});
                    break
                case "disclosure": //披露
                    wx.navigateTo({url: "/packageUser/pages/disclosure-list/index"});
                    break
                case "questionnaire": //调查问卷
                    let result = this.data.result;
                    remove({name: "questionnaire", observer: this});
                    addOnce({
                        name: "questionnaire",
                        callback: function (res) {
                            that.setData({result: res})
                        },
                        observer: this
                    })
                    if (result && result.level) {
                        wx.navigateTo({url: "/packageQuestionnaire/pages/result/result"});
                    } else {
                        wx.navigateTo({url: "/packageQuestionnaire/pages/list/list"});
                    }
                    break
            }
        } catch (e) {
            console.error(e)
        }
    },
    
    /*
    * 退出登录
    * 清空页面数据
    * */
    onSignOut: function () {
        removeStorageSync("token");
        this.setData({
            userInfo: {
                name: "",
                type: "",
                typeName: "",
                tel: ""
            },
            assets: {
                total: "",
                change: "",
                chiyou: 0,
                shuhui: 0,
                pilou: 0
            },
            showBottom: false
        })
    },

    /*
    * 修改密码
    * */
    bindRevisePassword: function () {
        const that = this;
        remove({name: "revisePassword", observer: this});
        addOnce({
            name: "revisePassword",
            callback: function (res) {
                that.onSignOut();
                Toast.loading({
                    duration: 0, // 持续展示 toast
                    message: "加载中...",
                    selector: "#van-toast"
                });
                that.getUserInfo();
            },
            observer: this
        })
        wx.navigateTo({url: "/packageUser/pages/revise-password/index"});
    },

    /*
    * 验证登录状态
    * */
    _checkedLogin: async function () {
        const that = this;
        let token = getStorageSync("token.value");
        if (!token) {
            await Dialog.alert({
                title: "提示",
                message: "请先登录"
            })
            Storage.setStorageSync("token.page", "/pages/user/index/index")
            wx.navigateTo({ //关闭当前页面 跳转tab页
                url: "/pages/user/login/index/index",
                events: {
                    acceptDataFromOpenedPage: function(data) {
                        Toast.loading({
                            duration: 0, // 持续展示 toast
                            message: "加载中...",
                            selector: "#van-toast"
                        });
                        data.login ? that.getUserInfo() : null;
                    }
                }
            });
            return false
        }
        return true
    },

    /*
    * 下拉刷新
    * */
    onPullDownRefresh: async function () {
        await this.getUserInfo();
        wx.stopPullDownRefresh();
    },
})